import { useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";

import { handleErrors } from "../utils/handleErrors";
import useAuth from "./useAuth";
import { useRouter } from "./useRouter";

const LOGIN = gql`
  mutation Login($user: LoginInput!) {
    login(user: $user) {
      user {
        username
      }
      authorities {
        name
      }
    }
  }
`;

const useLogin = ({ form }) => {
  const { setLoginUser } = useAuth();
  const { location, push } = useRouter();

  const [login] = useMutation(LOGIN, {
    onCompleted: ({ login }) => {
      setLoginUser(login);
      push((location.state && location.state.from.pathname) || "/");
    },
    onError: ({ graphQLErrors, networkError, form }) => {
      handleErrors({ graphQLErrors, networkError, form });
    }
  });

  const handleLogin = event => {
    event.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        login({ variables: { user: { ...values } } });
      }
    });
  };

  return {
    handleLogin
  };
};
export default useLogin;
